package com.answerz.module_reportissues.viewmodel

import android.text.TextUtils
import androidx.databinding.ObservableField
import com.czl.base.base.BaseBean
import com.czl.base.base.BaseViewModel
import com.czl.base.base.MyApplication
import com.czl.base.binding.command.BindingAction
import com.czl.base.binding.command.BindingCommand
import com.czl.base.data.DataRepository
import com.czl.base.data.bean.ComplaintDetailBean
import com.czl.base.data.bean.OrderDetailBean
import com.czl.base.data.bean.RepairListBean
import com.czl.base.data.bean.ReportOrderState
import com.czl.base.event.LiveBusCenter
import com.czl.base.event.SingleLiveEvent
import com.czl.base.extension.ApiSubscriberHelper
import com.czl.base.util.RxThreadHelper
import com.luck.picture.lib.entity.LocalMedia
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList

class ComplaintDetailViewModel(application: MyApplication, model: DataRepository) :
    BaseViewModel<DataRepository>(application, model) {
    var orderNo = ObservableField<String>("")
    var reportPersen = ObservableField<String>("")
    var reportPhone = ObservableField<String>("")
    var orderResponsible = ObservableField<String>("")
    var orderMaintainPhone = ObservableField<String>("")
    var orderContent = ObservableField<String>("")
    var orderAttach = ObservableField<ArrayList<LocalMedia>>(ArrayList<LocalMedia>())
    //    var orderState = ObservableField<String>("")
//    var orderStateFlow = ObservableField<ArrayList<ReportOrderState>>()
    var orderButtonText = ObservableField<String>("")
    var attachImagesEvent: SingleLiveEvent<ArrayList<LocalMedia>> = SingleLiveEvent()
    var orderStateFlowEvent: SingleLiveEvent<ArrayList<ReportOrderState>> = SingleLiveEvent()
    val refreshListEvent: SingleLiveEvent<Void> = SingleLiveEvent()
    val loadCompleteEvent: SingleLiveEvent<RepairListBean> = SingleLiveEvent()
    val cancelOrderEvent: SingleLiveEvent<String> = SingleLiveEvent()
    val deleteOrderEvent: SingleLiveEvent<String> = SingleLiveEvent()
    val navScoreEvent: SingleLiveEvent<String> = SingleLiveEvent()
    var onClickSubmit: BindingCommand<Any> = BindingCommand(BindingAction {
        dealOrder(orderButtonText.get().toString(), orderNo.get().toString())
    })
    val onRefreshListener: BindingCommand<Void> = BindingCommand(BindingAction {
        getData(orderNo.get().toString())
    })
    val onRefreshFinishEvent:SingleLiveEvent<Boolean> = SingleLiveEvent()
    fun hasAttach(pl: ArrayList<LocalMedia>): Boolean {
        if (pl == null || pl.size == 0) {
            return false
        }
        return true
    }

    fun getData(no: String) {
        model.getComplaintDetail(no)
            .compose(RxThreadHelper.rxSchedulerHelper(this))
            .doOnSubscribe { showLoading() }
            .subscribe(object : ApiSubscriberHelper<BaseBean<ComplaintDetailBean>>() {
                override fun onResult(t: BaseBean<ComplaintDetailBean>) {
                    dismissLoading()
                    if (t.code == 200) {
                        onRefreshFinishEvent.postValue(true)
                        var orderDetail = t.data
                        orderNo.set(orderDetail?.no)
                        reportPersen.set(orderDetail?.reporterName)
                        reportPhone.set(orderDetail?.reporterMobile)
                        orderResponsible.set(orderDetail?.handlerName)
                        orderMaintainPhone.set(orderDetail?.handlerMobile)
                        orderContent.set(orderDetail?.description)
                        var photolist = ArrayList<LocalMedia>()
                        for (item in orderDetail?.files!!) {
                            photolist.add(LocalMedia().apply { path = item
                                mimeType= if (item.endsWith(".mp4")) "video/mp4" else ""})
                        }
                        orderAttach.set(photolist)
                        attachImagesEvent.postValue(photolist)
                        var sls = ArrayList<ReportOrderState>()
                        for (item in orderDetail.operLogs) {
//                                if (TextUtils.equals(item.title,"待接单")
//                                    || TextUtils.equals(item.title,"已接单")
//                                    || TextUtils.equals(item.title,"处理完成")
//                                    || TextUtils.equals(item.title,"已审核")
//                                    || TextUtils.equals(item.title,"已评价")) {
                            var img=ArrayList<LocalMedia>()
                            if (item.files!=null&& item.files!!.isNotEmpty()){
                                for (i in item.files!!){
                                    img.add(LocalMedia().apply {
                                        path=i
                                        mimeType= if (i.endsWith(".mp4")) "video/mp4" else ""
                                    })
                                }
                            }
                            if (!item.title.equals("转单")){
                                sls.add(
                                    ReportOrderState(
                                        item.title, item.score, "", item.statusDescription,
                                        formatDateString(item.createTime), item.memo, img
                                    )
                                )
                            }
//                                }
                        }
                        setButtonText(appenState(sls, orderDetail.status))
                        orderStateFlowEvent.postValue(sls)
                    } else {
                        onRefreshFinishEvent.postValue(false)
                        showErrorToast(t.msg)
                    }
                }

                override fun onFailed(msg: String?) {
                    onRefreshFinishEvent.postValue(false)
                    dismissLoading()
                    showErrorToast(msg)
                }
            })
    }

    fun formatDateString(time: String): String {
        if (TextUtils.isEmpty(time)) {
            return ""
        }
        var df = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
        var df1 = SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.UK)
        var df2 = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        var date = df.parse(time)
        var date1 = df1.parse(date.toString())
        var date2 = df2.format(date1)
//        var date3=df2.format(date)
        return date2

    }

    fun appenState(sls: ArrayList<ReportOrderState>, state: Int): String {
        when (state) {
            0 -> {
                return "待受理"
            }
            1 -> {
                sls.add(ReportOrderState("待反馈", 0.0, "", "", "", "", null))
                return "待反馈"
            }
            2 -> {
                sls.add(ReportOrderState("待评价", 0.0, "", "", "", "", null))
                return "待评价"
            }
            3 -> {
                return "已评价"
            }
        }
        return ""
    }

    fun setButtonText(state: String) {
        orderButtonText.set("")
        when (state) {
            "待受理","待反馈" -> orderButtonText.set("撤销")
            "待评价" -> orderButtonText.set("评价")
            "已评价" -> orderButtonText.set("删除")

        }
    }

    fun dealOrder(state: String, orderNo: String) {
        when (state) {
            "撤销" -> cancelOrderEvent.postValue(orderNo)
            "评价" -> navScoreEvent.postValue(orderNo)
            "删除" -> deleteOrderEvent.postValue(orderNo)
        }
    }

    fun cancelComplaint(no: String) {
        model.cancelComplaint(no)
            .compose(RxThreadHelper.rxSchedulerHelper(this))
            .doOnSubscribe { showLoading() }
            .subscribe(object : ApiSubscriberHelper<BaseBean<Any?>>() {
                override fun onResult(t: BaseBean<Any?>) {
                    dismissLoading()
                    if (t.code == 200) {
                        LiveBusCenter.postCancelComplaintEvent(no)
                        showSuccessToast("撤销成功！")
                    } else {
                        showSuccessToast("撤销失败！")
                    }
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showErrorToast(msg)
                }

            })
    }

    fun deleteComplaint(no: String) {
        model.deleteComplaint(no)
            .compose(RxThreadHelper.rxSchedulerHelper(this))
            .doOnSubscribe { showLoading() }
            .subscribe(object : ApiSubscriberHelper<BaseBean<Any?>>() {
                override fun onResult(t: BaseBean<Any?>) {
                    dismissLoading()
                    if (t.code == 200) {
                        LiveBusCenter.postDeleteComplaintEvent(no)
                        showSuccessToast("删除成功！")
                    } else {
                        showSuccessToast("删除失败！")
                    }
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showErrorToast(msg)
                }

            })
    }
}